package com.lb.bigdata.util.db;

import com.lb.bigdata.util.CommonUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedList;

public class ConnectionPool {

    private static LinkedList<Connection> pool = new LinkedList<>();

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            for (int i = 0; i < 5; i++) {
                Connection connection = DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/test",
                        "root",
                        "root"
                );
                pool.push(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        while(pool.isEmpty()) {
            CommonUtil.sleep(1000);
        }
        return pool.poll();
    }

    public static void release(Connection connection) {
        pool.push(connection);
    }
}
